
package com.kweative.lingua.server.protocol;

import com.kweative.lingua.server.Config;
import com.kweative.lingua.server.ProtocolPool;
import com.kweative.lingua.server.exceptions.InvalidRequestException;
import com.kweative.lingua.server.structures.AppRequest;
import com.kweative.lingua.server.exceptions.NotFoundException;
import com.kweative.lingua.server.request.RequestHandler;
import com.kweative.lingua.server.response.ResponseHandler;
import com.kweative.network.Response;
import com.kweative.type.Node;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
abstract public class Protocol  implements Serializable {
    protected String[] reserved = {};
    abstract public boolean canRead(RequestHandler request);
    abstract public AppRequest[] read(RequestHandler request) throws NotFoundException;
    abstract public void writeException(ResponseHandler response,Throwable ex);
    abstract public void write(ResponseHandler response,Node result);
    
    public boolean isReserved(String word) {
        for(String test:reserved) {
            if (test.equals(word)) return true;
        }
        return false;
    }
    public boolean isReserved(String word,Protocol protocol) {
        return isReserved(word) || protocol.isReserved(word);
    }
    protected String getSessionIdName() {
        return (String) Config.instance().get(Config.SESSIONIDNAME);
    }
    protected Integer getSessionExpire() {
        return (Integer) Config.instance().get(Config.SESSIONEXPIRE)*1000;
    }

    public Protocol getDefaultResponse() {
        try {
            return (Protocol)this.getClass().newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ProtocolPool.instance().getDefaultProtocol();
    }

    public Node normalizeResponse(AppRequest appRequest, Node result) {
        return result;
    }
    public Node normalizeDocumentation(AppRequest appRequest, Node result) throws InvalidRequestException {
        return result;
    }
    public void writeDocumentation(ResponseHandler response,Node result) {
        write(response, result);
    }

}
